package br.ufu.si.dao;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateSessionUtil {
	
	private static SessionFactory sessionFactory;
	private static Session session;
	
	static {
		try {
			Configuration configuration = new Configuration();  
			configuration.configure();  
			ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();          
			sessionFactory = configuration.buildSessionFactory(serviceRegistry);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
		
	public static Session getSession(){
		if(session == null || !session.isOpen()){
			session = sessionFactory.openSession(); 
		}
		return session;
	}
	
	public static void close(){
		session.close();
	}
	
}
